package com.igeek.boot.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * @package com.igeek.boot.controller
 * @Description 配置数据源替换底层
 * @Author LittlePunk [296526219@qq.ccom]
 * @Version 2022.1
 * @Date 2023/12/11 13:09
 */
//@Configuration
public class DataSourceConfig {

    /**替换底层组件为druid数据源的步骤
     * 第一步：引入Druid的依赖
     * 第二步：@Configuration + @Bean 替换了底层的DataSource的bean实例
     * 第三步：@ConfigurationProperties 指定了操作前缀，可以在application.properties配置文件中绑定数据
     */
    //@Bean
    //@ConfigurationProperties(prefix = "spring.datasource")
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        //开启SQL监控、SQL防火墙监控、日志监控
        dataSource.setFilters("stat,wall,slf4j");
        return dataSource;
    }


    //StatViewServlet 开启Druid的内置监控页面
    //@Bean
    public ServletRegistrationBean<StatViewServlet> servletRegistrationBean(){
        StatViewServlet statViewServlet = new StatViewServlet();
        ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet , "/druid/*");
        //设置监控页面的登陆时的账号和密码
        registrationBean.addInitParameter("loginUsername" , "admin");
        registrationBean.addInitParameter("loginPassword" , "admin");
        //禁止记录日志重置曹总
        registrationBean.addInitParameter("resetEnable" , "false");
        return registrationBean;
    }

    //WebStatFilter 开启用于采集web-jdbc关联监控的数据
    //@Bean
    public FilterRegistrationBean<WebStatFilter> filterRegistrationBean(){
        WebStatFilter webStatFilter = new WebStatFilter();
        FilterRegistrationBean<WebStatFilter> registrationBean = new FilterRegistrationBean<>();
        registrationBean.setFilter(webStatFilter);
        //设置过滤路径
        registrationBean.setUrlPatterns(Stream.of("/*").collect(Collectors.toList()));
        //设置排除路径
        registrationBean.addInitParameter("exclusions" , "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return registrationBean;
    }
}
